#!/usr/bin/env python
# coding: utf-8

import pymongo
from pymongo import Connection
from celery.task import task
import bcrypt
from settings import settings


"""
MongoDB classes for accessing collections within the virtual congresscritter.
Each class pertains to a collection within the mongo database

"""


class content():
    pass


class link():
    pass


class user():
    pass


class n_gram():
    pass


def create_service(website, hooks, key):
    #creates a database specific to this website
    """
        Create a service for this website.
        Website must provide the following:
            hooks:
                *atomic user by id
                *atomic content by id
                *atomic preference by id
                *user list
                *content list
                *preference list

            for instance:
                {"get_user": "http://localhost:8000/api/user/%s/",
                "get_content": "http://localhost:8000/api/content/%s/%s/%s/",
                get_vote: "http://localhost:8000/api/votes/%s/%s/",
                get_vote_pks: "http://localhost:8000/api/pks/user/",
                get_content_pks: "http://localhost:8000/api/pks/content/",
                get_user_pks: "http://localhost:8000/api/pks/vote/",}
    """
    # Hash a password for the first time, with a randomly-generated salt
    hashed = bcrypt.hashpw(key, bcrypt.gensalt())

    # gensalt's log_rounds parameter determines the complexity.
    # The work factor is 2**log_rounds, and the default is 12
    hashed = bcrypt.hashpw(key, bcrypt.gensalt(10))

    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection.registrations
    coll = db['registrations']
    old = coll.find({'site': website})
    if old.count() == 0:
        new_site = {'site': website, 'hooks': hooks, 'hash': hashed}
        coll.insert(new_site)


def verify_key(website, key):
    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection.registrations
    coll = db['registrations']
    site = coll.find_one({'site': website})

    # Check that an unencrypted password matches one that has
    # previously been hashed
    if bcrypt.hashpw(key, site['hash']) == site['hash']:
        return True
    else:
        return False


def get_from_registrar(website, info):
    """Get info from registrar, based on 'info'
        list of keys to gather from the registration object"""
    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection.registrations
    coll = db['registrations']
    site = coll.find_one({'site': website})
    if site is None:
        raise ValueError('Site not found.')
    ret = {}
    for i in info:
        ret[i] = site[i]
    return ret


def save_item(website, collname, data):
    """Saves item 'data' for the 'website' db,
        in the collection 'key'"""
    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection[website.replace('/', '').replace('.', '')]
    coll = db[collname]
    coll.insert(data)


def update_item(website, collname, data):
    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection[website.replace('/', '').replace('.', '')]
    coll = db[collname]
    return coll.update({"id": int(data['id'])}, {"$set": data}, safe=True)


def get_item(website, collname, data=None):
    """Gets item 'data' for the 'website' db
        in the collection 'key'"""
    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection[website.replace('/', '').replace('.', '')]
    coll = db[collname]
    if data is not None:
        return list(coll.find(data))
    else:
        return list(coll.find())


def has_item(website, collname, pk):
    """Checks to see if an object['id'] == pk exists"""
    connection = Connection(settings['SERVER'], settings['PORT'])
    db = connection[website.replace('/', '').replace('.', '')]
    coll = db[collname]
    old = coll.find({'id': pk})
    if old.count() > 0:
        return True
    else:
        return False
